﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Carpool1.Models;
using System.Data.Entity;

namespace Carpool.Controllers
{
    public class HomeController : Controller
    {
        CarpoolEntities db=new CarpoolEntities();
        // 首页：显示最新拼车信息
        // 首页：显示最新拼车信息
        public async Task<ActionResult> Index(int? type, string startCity, string endCity)
        {
            // 构建查询条件
            var query = db.CarpoolInfo.AsQueryable();

            // 筛选条件（优化：当type=0时不筛选类型）
            if (type.HasValue && type.Value > 0)
            {
                query = query.Where(c => c.InfoType == type.Value);
            }

            // 出发地和目的地筛选（优化：支持空值处理）
            if (!string.IsNullOrEmpty(startCity))
            {
                query = query.Where(c => c.StartCity.Contains(startCity));
            }
            if (!string.IsNullOrEmpty(endCity))
            {
                query = query.Where(c => c.EndCity.Contains(endCity));
            }

            // 按发布时间降序排列
            var carpools = await query
                .Where(c => c.Status == 1) // 只显示有效状态
                .OrderByDescending(c => c.PublishTime)
                .ToListAsync();

            // 加载筛选条件到视图
            ViewBag.Types = new SelectList(new[] {
                new { Value = 0, Text = "全部类型" },
                new { Value = 1, Text = "长途拼车" },
                new { Value = 2, Text = "短途拼车" }
            }, "Value", "Text", type);
            ViewBag.StartCity = startCity;
            ViewBag.EndCity = endCity;

            // 检查是否有拼车信息
            if (!carpools.Any())
            {
                ViewBag.NoResultMessage = "没有找到符合条件的拼车信息";
            }

            return View(carpools);
        }

        // 拼车搜索（异步加载）
        public async Task<ActionResult> _CarpoolList(int? type, string startCity, string endCity)
        {
            var query = db.CarpoolInfo.AsQueryable();

            // 筛选条件（优化：当type=0时不筛选类型）
            if (type.HasValue && type.Value > 0)
            {
                query = query.Where(c => c.InfoType == type.Value);
            }

            // 出发地和目的地筛选
            if (!string.IsNullOrEmpty(startCity))
            {
                query = query.Where(c => c.StartCity.Contains(startCity));
            }
            if (!string.IsNullOrEmpty(endCity))
            {
                query = query.Where(c => c.EndCity.Contains(endCity));
            }

            var result = await query
                .Where(c => c.Status == 1)
                .OrderByDescending(c => c.PublishTime)
                .ToListAsync();

            // 加载筛选条件到视图
            ViewBag.Types = new SelectList(new[] {
                new { Value = 0, Text = "全部类型" },
                new { Value = 1, Text = "长途拼车" },
                new { Value = 2, Text = "短途拼车" }
            }, "Value", "Text", type);
            ViewBag.StartCity = startCity;
            ViewBag.EndCity = endCity;

            // 检查是否有拼车信息
            if (!result.Any())
            {
                ViewBag.NoResultMessage = "没有找到符合条件的拼车信息";
            }

            return PartialView("_CarpoolList", result);
        }

        // 拼车详情
        public async Task<ActionResult> Detail(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
            }

            var carpool = await db.CarpoolInfo
                .Include(c => c.User) // 加载车主信息
                .FirstOrDefaultAsync(c => c.InfoID == id && c.Status == 1);

            if (carpool == null)
            {
                return HttpNotFound();
            }

            // 检查是否已关注
            // 1. 提取 Session 值到变量（处理 null 情况）
            int? userId = null;
            if (Session["UserID"] != null)
            {
                userId = (int)Session["UserID"];
            }

            // 2. 使用变量参与 LINQ 查询
            if (userId.HasValue)
            {
                ViewBag.IsFollowed = db.CarpoolFollow
                    .Any(f =>
                        f.UserID == userId.Value &&  // 用变量，避免直接使用 Session
                        f.TargetType == 1 &&
                        f.TargetID == id
                    );
            }
            else
            {
                // Session 中无 UserID（未登录）
                ViewBag.IsFollowed = false;
            }

            // 加载相似拼车（同起点终点）
            var similarCarpools = await db.CarpoolInfo
                .Where(c =>
                    c.InfoID != id &&
                    c.StartCity == carpool.StartCity &&
                    c.EndCity == carpool.EndCity &&
                    c.Status == 1)
                .OrderByDescending(c => c.PublishTime)
                .Take(3)
                .ToListAsync();
            ViewBag.SimilarCarpools = similarCarpools;

            return View(carpool);
        }
        // 辅助方法：车型转换（放控制器或单独工具类）
        private string GetCarTypeText(int type)
        {
            switch (type)
            {
                case 1: return "轿车";
                case 2: return "SUV";
                case 3: return "MPV";
                case 4: return "客车";
                default: return "其他";
            }
        }

        // 拼车地图视图
        public ActionResult Map()
        {
            return View();
        }

        // 获取拼车地图数据（API）
        [HttpGet]
        public async Task<JsonResult> GetCarpoolMapData()
        {
            var carpools = await db.CarpoolInfo
                .Where(c => c.Status == 1)
                .Select(c => new
                {
                    c.InfoID,
                    c.StartCity,
                    c.EndCity,
                    c.DepartureTime,
                    c.Fee,
                    c.FeeType,
                    OwnerName = c.User.RealName ?? c.User.PhoneNumber.Substring(7)
                })
                .ToListAsync();

            return Json(carpools, JsonRequestBehavior.AllowGet);
        }

        // 关于我们
        public ActionResult About()
        {
            ViewBag.Message = "拼车网 - 安全、便捷、环保的出行方式";
            return View();
        }

        // 联系我们
        public ActionResult Contact()
        {
            ViewBag.Message = "如有问题，请联系我们";
            return View();
        }

        // 释放资源
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}